package com.bawei.day18_mediaplayer;

import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.lauzy.freedom.library.Lrc;
import com.lauzy.freedom.library.LrcHelper;
import com.lauzy.freedom.library.LrcView;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import androidx.appcompat.app.AppCompatActivity;

/**
 * mediaplayer:音乐播放器+视频播放器
 * 1。设置媒体资源
 * 2。播放
 * 3。暂停
 * 4。停止
 * 5。进度条
 * 6。播放时间显示
 * 7。上一首 下一首
 * 8。播放模式切换：单曲 顺序 随机
 * 9。歌词
 */
public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private Button bt_play;
    private Button bt_pause;
    private Button bt_stop;
    private Button bt_pre;
    private Button bt_next;
    private Button bt_shunxu;
    private Button bt_suiji;
    private Button bt_danqu;

    private MediaPlayer mediaPlayer = new MediaPlayer();
    private Timer timer;
    private SeekBar seekBar;
    private TextView tv_duration, tv_current;
    private List<String> list = new ArrayList<>();//所有的歌曲
    private int position = 0;//默认播放第几首
    private int mode = 0;//播放模式 0：顺序播放 1：随机播放 2：单曲循环

    private LrcView lrcView;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            requestPermissions(new String[]{
                    "android.permission.WRITE_EXTERNAL_STORAGE",
                    "android.permission.READ_EXTERNAL_STORAGE"
            }, 101);
        }
        list.add("/sdcard/Music/吴若希-越难越爱.mp3");
        list.add("/sdcard/Music/欢子-保重.mp3");
        list.add("/sdcard/Music/沙宝亮-友情卡片.mp3");
        list.add("/sdcard/Music/白举纲-我是一只鱼.mp3");
        initView();
        play();//页面一打开就播放歌曲
        initTimer();//定时器：进度条+播放时间
        List<Lrc> lrcs = LrcHelper.parseLrcFromFile(new File("/sdcard/Music/吴若希-越难越爱.lrc"));
        lrcView.setLrcData(lrcs);


    }

    private void initTimer() {
        timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                final int duration = mediaPlayer.getDuration();//获取歌曲的总时长
                final int currentPosition = mediaPlayer.getCurrentPosition();//获得歌曲的当前进度
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        seekBar.setMax(duration);
                        seekBar.setProgress(currentPosition);
                        //将毫秒---》格式化为 00:00
                        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("mm:ss");
                        tv_duration.setText(simpleDateFormat.format(duration));
                        tv_current.setText(simpleDateFormat.format(currentPosition));

                        lrcView.updateTime(currentPosition);
                    }
                });


            }
        }, 0, 1000);
    }
    //播放歌曲
    private void play() {
        try {
            mediaPlayer.reset();//重置注意！！！！！！！！！！
            mediaPlayer.setDataSource(list.get(position));//设置媒体资源
            mediaPlayer.prepare();//准备
            mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {//准备监听
                @Override
                public void onPrepared(MediaPlayer mp) {//准备完毕
                    mediaPlayer.start();//播放音乐


                }
            });
            mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {//音乐播放完毕
                @Override
                public void onCompletion(MediaPlayer mp) {
                    if(mode == 0){//顺序播放
                        if (position == list.size()-1){//是否是最后一首歌曲
                            position = 0;
                        }else{
                            position++;
                        }
                        play();
                    }else if (mode == 1){//随机播放 0-size-1
                        position = (int) (Math.random()*list.size());
                        play();
                    }else if(mode == 2){//单曲循环
                        play();
                    }
                    Toast.makeText(MainActivity.this, "播放完毕", Toast.LENGTH_SHORT).show();
                }
            });
            mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {//播放失败
                @Override
                public boolean onError(MediaPlayer mp, int what, int extra) {
                    Toast.makeText(MainActivity.this, "音乐加载失败", Toast.LENGTH_SHORT).show();
                    return false;
                }
            });


        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void initView() {
        lrcView = findViewById(R.id.lrc);
        bt_play = (Button) findViewById(R.id.bt_play);
        bt_pause = (Button) findViewById(R.id.bt_pause);
        bt_stop = (Button) findViewById(R.id.bt_stop);
        tv_duration = findViewById(R.id.tv_duration);
        tv_current = findViewById(R.id.tv_current);
        bt_pre = (Button) findViewById(R.id.bt_pre);
        bt_pre.setOnClickListener(this);
        bt_next = (Button) findViewById(R.id.bt_next);
        bt_next.setOnClickListener(this);
        bt_shunxu = (Button) findViewById(R.id.bt_shunxu);
        bt_shunxu.setOnClickListener(this);
        bt_suiji = (Button) findViewById(R.id.bt_suiji);
        bt_suiji.setOnClickListener(this);
        bt_danqu = (Button) findViewById(R.id.bt_danqu);
        bt_danqu.setOnClickListener(this);

        seekBar = findViewById(R.id.bar);
        bt_play.setOnClickListener(this);
        bt_pause.setOnClickListener(this);
        bt_stop.setOnClickListener(this);
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (fromUser) {//来自用户的拖拽 而不是自己走的
                    mediaPlayer.seekTo(progress);//音乐播放到指定的进度
                }

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
        lrcView.setOnPlayIndicatorLineListener(new LrcView.OnPlayIndicatorLineListener() {
            @Override
            public void onPlay(long time, String content) {
                mediaPlayer.seekTo((int) time);
            }
        });

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bt_play:
                if (mediaPlayer != null) {
                    mediaPlayer.start();//播放
                }
                break;
            case R.id.bt_pause:
                if (mediaPlayer != null) {
                    mediaPlayer.pause();//暂停
                }
                break;
            case R.id.bt_stop:
                if (mediaPlayer != null) {
                    mediaPlayer.stop();//停止 停止后
                }
                break;
            case R.id.bt_pre://上一首
                if(mode == 0){//顺序播放
                    if (position == 0){//是否是第一首歌曲
                        position = list.size()-1;
                    }else{
                        position--;
                    }
                    play();
                }else if (mode == 1){//随机播放 0-size-1
                    position = (int) (Math.random()*list.size());
                    play();
                }else if(mode == 2){//单曲循环
                    play();
                }
                break;
            case R.id.bt_next://下一首
                if(mode == 0){//顺序播放
                    if (position == list.size()-1){//是否是最后一首歌曲
                        position = 0;
                    }else{
                        position++;
                    }
                    play();
                }else if (mode == 1){//随机播放 0-size-1
                    position = (int) (Math.random()*list.size());
                    play();
                }else if(mode == 2){//单曲循环
                    play();
                }

                break;
            case R.id.bt_shunxu://顺序播放
                mode = 0;
                break;
            case R.id.bt_suiji://随机播放
                mode = 1;
                break;
            case R.id.bt_danqu://单曲循环
                mode = 2;
                break;
        }
    }

    @Override
    protected void onDestroy() {//销毁音乐
        super.onDestroy();
        if (mediaPlayer != null) {
            mediaPlayer.release();//释放资源
            mediaPlayer = null;//垃圾回收机制会自动回收
        }
        if (timer != null) {
            timer.cancel();
        }
    }
}
